package io.gitee.icefairy.ice_license

import cn.hutool.core.date.DateUtil
import cn.hutool.log.LogFactory
import cn.hutool.setting.Setting
import io.gitee.icefairy.ice_license.LicenseUtil
import io.gitee.icefairy.ice_license.model.License
import java.io.File
import java.util.*
import kotlin.system.exitProcess

fun main(args: Array<String>) {
    val argExamples = mapOf<String, String>(
        "client" to "标识此证书是给哪个客户的",
        "product" to "标识此证书是给哪个产品的",
        "start" to "可选：有效期开始日期，例如：2021-11-20注意如果填写了此日期，在未到此日期的时候无法通过认证",
        "end" to "有效期终止日期，例如：2021-11-22",
        "mac" to "可选：绑定mac地址，例如8C-EC-4B-7B-F6-0F",
        "ip" to "可选：绑定ipv4地址，例如192.168.1.1",
        "boardserial" to "可选：主板序列号例如123456"
    )
    val app = LicGen()
    app.checkSetting()
    if (args.isEmpty()) {
        println(
            """使用帮助:
            |${
                argExamples.keys.joinToString("\n") {
                    it + "=" + argExamples.get(it)
                }
            }
        |请妥善保管好私钥内容，公钥是随客户端软件分发出去的。
        """.trimMargin()
        )
        exitProcess(0)
    } else {
        val req = Setting()
        args.forEach {
            val ss = it.split("=")
            if (ss.size == 2) {
                if (argExamples.containsKey(ss[0])) {
                    req.put(ss[0], ss[1])
                }
            }
        }
        app.genLicense(req)
    }
}

class LicGen {
    val log = LogFactory.get()
    var set: Setting = Setting()
    fun checkSetting() {
        if (!File("./set.ini").exists()) {
            log.info("初次运行，自动生成证书中……")
            val rsa = LicenseUtil.genRSAKey() ?: throw RuntimeException("无法生成证书")
            set.put("privateKey", rsa.privateKeyBase64)
            set.put("publicKey", rsa.publicKeyBase64)
            set.store(File("./set.ini"))
        } else {
            set = Setting(File("./set.ini").absolutePath)
        }
    }

    fun genLicense(req: Setting) {
        val lc = License()
        lc.clientName = req.getStr("client")
        lc.product = req.getStr("product")
        lc.start = DateUtil.parseDateTime(req.getStr("start") ?: DateUtil.formatDate(Date()) + " 00:00:00").toJdkDate()
        lc.end = DateUtil.parseDateTime(req.getStr("end") + " 00:00:00").toJdkDate()
        lc.boardSerial = req.getStr("boardserial", null)
        lc.ip = req.getStr("ip", null)
        lc.mac = req.getStr("mac", null)
        val encLc = LicenseUtil.genLicenseForClient(lc, set.getStr("privateKey"))
        if (!File("./certs").exists() || !File("./certs").isDirectory) {
            File("./certs").mkdir()
        }
        val f = File("./certs/${req.getStr("product")}_${req.getStr("client")}_${req.getStr("end")}.key")
        f.bufferedWriter()?.use {
            it.write(encLc)
            it.flush()
        }
        log.info("证书已生成:${f.absolutePath}")
    }

}